package controller.ur;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import model.dao.PhotoDaoLocal;
import model.dao.RatingDaoLocal;
import model.entity.Photo;
import model.entity.Rating;
import model.entity.User;
import controller.CUtil;

/**
 * Servlet implementation class SPhotoAddRating
 */
public class SPhotoAddRating extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	@EJB
	private RatingDaoLocal ratingDao;
	
	@EJB
	private PhotoDaoLocal photoDao;
	
	private Logger log=Logger.getLogger(SPhotoAddRating.class);
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SPhotoAddRating() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(!CUtil.checkLogIn(request, response))
			return;
		
		int id=Integer.parseInt((String)request.getParameter("id"));
		User user=(User)request.getSession().getAttribute("user");
		Photo photo=photoDao.findById(id);
		int rate=Integer.parseInt((String)request.getParameter("rate"));
		Rating rating=new Rating();
		rating.setPhoto(photo);
		rating.setUser(user);
		rating.setVote(rate);
		photo.getRatings().add(rating);
		ratingDao.persist(rating);
		photoDao.merge(photo);
		double avgRate=0;
		int rateCount=0;
		for(Rating r:photo.getRatings()){
			avgRate+=r.getVote();
			rateCount++;
		}
		avgRate/=rateCount;
		photo.setRating(avgRate);
		photoDao.merge(photo);
		log.info("Rating added: "+rating.toString());
		CUtil.redirecter(request, response, "SViewPhoto?photoId="+id);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
